package com.bill.concurrency.strings;

import com.bill.concurrency.annotations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * StringBuilder是线程不安全的。
 */
@Slf4j
@NotThreadSafe
public class StringExample1 {
    private static int clientTotal=5000;
    private static int threadTotal=200;
    private static StringBuilder sb=new StringBuilder();

    public static void main(String[] args) {
        final ExecutorService executorService=Executors.newCachedThreadPool();
        final CountDownLatch countDownLatch=new CountDownLatch(clientTotal);
        final Semaphore semaphore=new Semaphore(threadTotal);
        for(int i=0;i<clientTotal;i++){
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    update();
                    semaphore.release();
                } catch (InterruptedException e) {
                   log.error("error:{}",e);
                }
                countDownLatch.countDown();
            });


        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            log.error("error:{}",e);
        }

        log.info("当前sb的长度是{}",sb.length());

    }

    private static void update(){
        sb.append("1");
    }
}
